﻿Imports System
Imports System.Threading
Imports log4net
Imports Equipment.Business

Public Class NotificationService
    Private Shared logger As ILog = LogManager.GetLogger(GetType(NotificationService))

    Private Const sleepTime As Integer = 30000
    Private Const attempt As Integer = 5

    Private Shared InProcess As Boolean = False
    Private Shared ToRun As Boolean = True

    Public Shared Sub Run()
        ToRun = True
        If Not InProcess Then
            Dim main As Thread = New Thread(AddressOf Process)
            main.Start()
        End If
    End Sub

    Public Shared Sub StopService()
        ToRun = False
        For i As Integer = 0 To attempt
            If InProcess = False Then
                Return
            End If
            Thread.Sleep(sleepTime)
        Next
        logger.Error("Notification Service cannot be stopped")
        Throw New TimeoutException("Service cannot be stopped")
    End Sub

    Private Shared Sub Process()
        Try
            InProcess = True
            While (ToRun)
                Try
                    NotificationManager.SendNotificationBySchedule()
                Catch ex As Exception
                    logger.Error(ex.Message + ":" + ex.StackTrace)
                End Try
                Thread.Sleep(sleepTime)
            End While
        Catch ex As Exception
            logger.Error(ex.Message + ":" + ex.StackTrace)
        End Try
        InProcess = False
    End Sub

End Class
